package com.zhiqianbao.utils;

import android.util.Log;

import org.apache.commons.codec.binary.Hex;

import java.security.MessageDigest;

/**
 * MD5加密工具类.
 * 
 * 返回String，统一编码为Hex
 * 
 * @author calvin
 */
public class Digests {

	public static final String MD5 = "MD5";
	//默认加密算法
	public static final String HASH_ALGORITHM = MD5;
	//默认迭代次数
	public static final int HASH_INTERATIONS = 2;
	
	private static final String DEFAULT_ENCODING = "UTF-8";

	/**
	 * 对输入字符串进行md5散列.
	 */
	public static String md5(String input) {
		return digest(input, MD5, null, 1);
	}

	public static String md5(String input, String salt) {
		return digest(input, MD5, salt, HASH_INTERATIONS);
	}

	public static String md5(String input, String salt, int iterations) {
		return digest(input, MD5, salt, iterations);
	}

	/**
	 * 对字符串进行散列, 支持md5与sha1算法.
	 */
	private static String digest(String input, String algorithm, String salt, int iterations) {
		try {
			MessageDigest digest = MessageDigest.getInstance(algorithm);

			if (salt != null) {
				digest.update(salt.getBytes(DEFAULT_ENCODING));
			}
			byte[] result = digest.digest(input.getBytes(DEFAULT_ENCODING));

			for (int i = 1; i < iterations; i++) {
				digest.reset();
				result = digest.digest(result);
			}
			return new String(Hex.encodeHex(result));
		} catch (Exception e) {
			if (e instanceof RuntimeException) {
				throw (RuntimeException) e;
			} else {
				throw new RuntimeException(e);
			}
		}
	}

	public static void main(String[] args) {
		System.out.println(Digests.md5("123456", "MD5", Digests.HASH_INTERATIONS));
		Log.i("Jiamissss",Digests.md5("123456", "MD5", Digests.HASH_INTERATIONS));
	}
}
